package com.neusoft.nep.SystemAdminstrator.Controller;

import com.neusoft.nep.SystemAdminstrator.Common.FileUtills;
import com.neusoft.nep.entity.GirdFeedback;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

public class Aqidistributetotalstatis {
    @FXML
    private Button btn_out;
    @FXML
    private Label levelOneCount;  // 一级数量（优）
    @FXML
    private Label levelTwoCount;  // 二级数量（良）
    @FXML
    private Label levelThreeCount; // 三级数量（轻度污染）
    @FXML
    private Label levelFourCount;  // 四级数量（中度污染）
    @FXML
    private Label levelFiveCount;  // 五级数量（重度污染）
    @FXML
    private Label levelSixCount;   // 六级数量（严重污染）

    @FXML
    private MenuItem mi_PSL, mi_AQI, mi_PGC, mi_AqiDistribute, mi_Other, mi_AqiTrendTotal;

    // 等级文本与数字的映射（用于解析 GirdFeedback 中的 level 属性）
    private static final Map<String, Integer> LEVEL_TEXT_TO_NUM = new HashMap<>();
    static {
        LEVEL_TEXT_TO_NUM.put("一级", 1);
        LEVEL_TEXT_TO_NUM.put("二级", 2);
        LEVEL_TEXT_TO_NUM.put("三级", 3);
        LEVEL_TEXT_TO_NUM.put("四级", 4);
        LEVEL_TEXT_TO_NUM.put("五级", 5);
        LEVEL_TEXT_TO_NUM.put("六级", 6);
    }

    @FXML
    public void initialize() {
        updateAqiLevelCounts(); // 初始化时统计数据
    }

    /**
     * 核心方法：遍历所有网格员文件，统计各 AQI 等级数量并更新 UI
     */
    public void updateAqiLevelCounts() {
        // 初始化各等级计数器为 0
        Map<Integer, Integer> levelCounts = new HashMap<>();
        for (int i = 1; i <= 6; i++) {
            levelCounts.put(i, 0);
        }

        // 获取所有网格员文件名（格式：girdxxxback.txt）
        List<String> officerFiles = getOfficerFileNames();

        // 遍历每个网格员文件，统计等级数量
        for (String fileName : officerFiles) {
            if (fileName.endsWith("back.txt")) {
                try {
                    // 读取文件中的反馈数据（Map 结构）
                    Map<String, GirdFeedback> feedbackMap = (Map<String, GirdFeedback>)
                            FileUtills.readMapObject(fileName);

                    // 遍历文件中的每条反馈，统计 level 等级
                    if (feedbackMap != null) {
                        for (GirdFeedback feedback : feedbackMap.values()) {
                            if (feedback != null) {
                                String levelText = feedback.getLevel();
                                Integer levelNum = LEVEL_TEXT_TO_NUM.get(levelText);
                                if (levelNum != null) {
                                    levelCounts.put(levelNum, levelCounts.get(levelNum) + 1);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showAlert("读取文件 " + fileName + " 失败，已跳过");
                }
            }
        }

        // 更新 UI 显示统计结果
        updateLabels(levelCounts);
    }

    /**
     * 获取当前目录下所有网格员反馈文件（girdxxxback.txt）
     */
    private List<String> getOfficerFileNames() {
        List<String> fileNames = new ArrayList<>();
        File directory = new File("."); // 当前工作目录
        File[] files = directory.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().startsWith("gird") &&
                        file.getName().endsWith("back.txt")) {
                    fileNames.add(file.getName());
                }
            }
        }
        return fileNames;
    }

    /**
     * 更新 UI 标签显示各等级数量
     */
    private void updateLabels(Map<Integer, Integer> levelCounts) {
        Platform.runLater(() -> {
            levelOneCount.setText(String.valueOf(levelCounts.getOrDefault(1, 0)));
            levelTwoCount.setText(String.valueOf(levelCounts.getOrDefault(2, 0)));
            levelThreeCount.setText(String.valueOf(levelCounts.getOrDefault(3, 0)));
            levelFourCount.setText(String.valueOf(levelCounts.getOrDefault(4, 0)));
            levelFiveCount.setText(String.valueOf(levelCounts.getOrDefault(5, 0)));
            levelSixCount.setText(String.valueOf(levelCounts.getOrDefault(6, 0)));
        });
    }

    /**
     * 显示警告对话框
     */
    private void showAlert(String message) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("警告");
            alert.setHeaderText(null);
            alert.setContentText(message);
            alert.showAndWait();
        });
    }

    // 以下为界面跳转方法
    public void OUT(ActionEvent actionEvent) {
        System.exit(0);
    }

    public void PSLClick(ActionEvent event) throws IOException {
        loadFXML("../View/publicList.fxml");
    }

    public void AQIListClick(ActionEvent event) throws IOException {
        loadFXML("../View/AQImakesure.fxml");
    }

    public void PGCClick(ActionEvent event) throws IOException {
        loadFXML("../View/ProvincialGroupComponentItemInspectionStatistics.fxml");
    }

    public void AqiDistributeClick(ActionEvent event) throws IOException {
        loadFXML("../View/AqiDistributeTotalStatisView.fxml");
    }

    public void OtherClick(ActionEvent event) throws IOException {
        loadFXML("../View/OtherTotalStatisView.fxml");
    }

    public void AqiTrendClick(ActionEvent event) throws IOException {
        loadFXML("../View/AqiTrendTotalStatisView.fxml");
    }

    /**
     * 通用 FXML 加载方法
     */
    private void loadFXML(String fxmlPath) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource(fxmlPath);
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_out.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }
}